package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"perm-guard/cache"
	"perm-guard/models"
	"strconv"
	"time"
)

func CarTypeList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))

	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))

	Offset := (page - 1) * size
	/*
		        SELECT
			  car_data.id AS DataId,
			  car_data.car_no AS CarNo,
			  car_data.car_name AS CarName,
			  car_data.car_price AS CarPrice,
			  car_types.type_code AS TypeCode,
			  car_types.type_name AS TypeName
			FROM
			  car_data
			  LEFT JOIN car_types ON car_types.id = car_data.tid
	*/
	var list []models.CarDataList

	redis_key := "con_list" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("car_data").
			Select(
				"car_data.id AS DataId",
				"car_data.car_no AS CarNo",
				"car_data.car_name AS CarName",
				"car_data.car_price AS CarPrice",
				"car_types.type_code AS TypeCode",
				"car_types.type_name AS TypeName",
			).
			Joins("LEFT JOIN car_types ON car_types.id = car_data.tid").
			Offset(Offset).
			Limit(size).
			Debug().
			Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}

	var total int64
	models.DB.Model(&models.CarData{}).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"list":  list,
		"total": total,
	})
	return

}
func CarTypeDetail(c *gin.Context) {
	id := c.Query("id")

	var list models.CarDataList

	redis_key := "con_detail" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("car_data").
			Select(
				"car_data.id AS DataId",
				"car_data.car_no AS CarNo",
				"car_data.car_name AS CarName",
				"car_data.car_price AS CarPrice",
				"car_types.type_code AS TypeCode",
				"car_types.type_name AS TypeName",
			).
			Joins("LEFT JOIN car_types ON car_types.id = car_data.tid").
			Where("car_data.id=?", id).
			Debug().
			Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"list": list,
	})
	return
}
